<?php
/**
 * ============================================================================
 * Copyright (c) 2015-2018 贵州大师兄信息技术有限公司 All rights reserved.
 * siteַ: http://www.dsxcms.com
 * ============================================================================
 * @author:     David Song<songdewei@163.com>
 * @version:    v1.0.0
 * ---------------------------------------------
 * Date: 2018/9/15
 * Time: 下午11:47
 */

namespace App\Library\Mall;


use App\Events\OrderEvent;
use App\Library\AuthenticatedUser;
use App\Models\Item;
use App\Models\Order;
use Illuminate\Http\Request;

trait AuctionTrait
{

    use AuthenticatedUser;

    protected function buildSingleOrder(Request $request)
    {
        $itemid = $request->input('itemid');
        $quantity = intval($request->input('quantity'));

        $item = Item::find($itemid);
        if ($item) {
            if (!$item->on_sale){
                return $this->itemNotFondResponse();
            }
            $item->quantity = max([1, $quantity]);
            $creator = new OrderCreator();
            $creator->shop         = $item->shop;
            $creator->items        = [$item];
            $creator->payType      = $request->input('pay_type', '1');
            $creator->shippingType = $request->input('shipping_type', '1');
            $creator->addressId    = $request->input('address_id', 0);
            $creator->buyerMessage = $request->input('buyer_message', '');
            $creator->invoice = $request->input('invoice', []);

            try{
                $order = $creator->create();
                event(new OrderEvent($order, 'created'));
                return $this->buildOrderSuccess($order);
            }catch (\Exception $e) {
                return $e;
            }
        } else {
            return $this->itemNotFondResponse();
        }
    }

    public function settlement(Request $request)
    {
        $address_id    = $request->post('address_id', '0');
        $pay_type      = $request->post('pay_type', '1');
        $shipping_type = $request->post('shipping_type', '1');
        $buyer_message = $request->post('buyer_message', []);

        $items = $request->post('items');
        $shops = $this->user()->cartItems()->with(['items'=>function($query){
            return $query->where('uid', $this->user()->uid);
        }])->whereIn('itemid', $items)->groupBy('shop_id')->get(['shop_id','shop_name']);

        foreach ($shops as $shop) {
            $creator = new OrderCreator();
            $creator->shop  = $shop->shop;
            $creator->items = $shop->items;
            $creator->addressId    = $address_id;
            $creator->payType      = $pay_type;
            $creator->shippingType = $shipping_type;
            $creator->buyerMessage = isset($buyer_message[$shop->shop_id]) ? $buyer_message[$shop->shop_id] : '';
            $creator->invoice = $request->input('invoice', []);

            try {
                $order = $creator->create();
                event(new OrderEvent($order, 'created'));
            } catch (\Exception $e){

            }
        }
        //清空购物车
        $this->user()->cartItems()->whereIn('itemid', $items)->delete();
        return $this->settlementResponse();
    }

    protected function itemNotFondResponse(){
        return response('item not found');
    }

    protected function buildOrderSuccess(Order $order)
    {
        return ajaxReturn(['order'=>$order]);
    }

    protected function buildOrderFailed(\Exception $exception)
    {
        return ajaxError($exception->getCode(), $exception->getMessage());
    }

    protected function settlementResponse()
    {
        return redirect('/user/trade/bought');
    }
}
